<?php
/*
 * find查找
 * @author     Mark <zhaody901@126.com>
 * @copyright  Copyright (c) 2013 lemon team
 * @version    $Id: 9390599e86623c380ef7187d4eb34aeea3ec9e9b $
 * @time       14-2-7 上午10:29
 */
class RecordFind
{
	private $_pagesize = 20;
	static $tables = array(
		'mall',
		'sell',
		'company',
		'job',
		'resume'
		);
	private $_type;
	private $_db;
	private $_table;
	private $_cfg;
	private $_count;

	/**
	 * 分页数量
	 * @return int
	 */
	private function getPagesize()
	{
		return $this->_pagesize;
	}

	/**
	 * constructor
	 * @param $type
	 */
	public function __construct($type)
	{
		global $db, $CFG;
		$this->_db = $db;
		$this->_cfg = $CFG;
		if (in_array($type, self::$tables)) {
			$this->_type = $type;
		} else {
			die('invalible Request!');
		}
		$this->_table =  $this->_cfg['tb_pre'].$this->_type;
	}

	/**
	 * 获取sql
	 * @param $page
	 * @param $kw
	 * @return string
	 */
	private function _getSql($page, $kw)
	{
		$page = intval($page);
		$limitStart = ($page-1) * $this->getPagesize();
		$limitEnd = ($page) * $this->getPagesize();
		$sql = 'SELECT ' . $this->_getFields() . ' FROM `' . $this->_table . '` WHERE ' . $this->_getLike($kw);
		$sql .= $this->_getOrder();
		$sql .= " LIMIT {$limitStart}, {$limitEnd}";
		//echo $sql;
		return $sql;
	}

	/**
	 * 获取字段
	 * @return string
	 */
	private function _getFields()
	{
		if ($this->_type == 'company') {
			return ' `userid`,`company`, `linkurl` ';
		} else {
			return ' `itemid`,`title`, `linkurl` ';
		}
	}

	/**
	 * 获取相似值
	 * @param $kw
	 * @return string
	 */
	private function _getLike($kw)
	{
		if ($this->_type == 'company') {
			$like = ' `company` LIKE "%'.$kw.'%"';
		} else {
			$like = ' `title` LIKE "%'.$kw.'%"';
		}
		return $like;
	}

	/**
	 * 获取排序
	 * @return string
	 */
	private function _getOrder()
	{
		if ($this->_type == 'company') {
			$order = ' ORDER BY groupid DESC ';
		} elseif($this->_type == 'resume') {
			$order = ' ORDER BY edittime DESC ';
		} else {
			$order = ' ORDER BY groupid DESC, edittime DESC ';
		}
		return $order;
	}

	/**
	 * 获取数量
	 * @param $kw
	 * @return int
	 */
	public function getCount($kw)
	{
		$like = $this->_getLike($kw);
		$this->_count = $this->_db->count($this->_table, $like);
		return $this->_count;
	}

	/**
	 * 获取结果
	 * @param $page
	 * @param $kw
	 * @return array
	 */
	public function getResults($page, $kw)
	{
		$sql = $this->_getSql($page, $kw);
		$results = $this->_db->query($sql, 'CACHE');
		$finds = array();
		while ($r = $this->_db->fetchArray($results)) {
			array_push($finds, $r);
		}
		return $finds;
	}

	/**
	 * 获取分页
	 * @param $page
	 * @return null|string
	 */
	public function getPages($page)
	{
		$pages = null;
		if ($this->_count) {
			$pages = pages($this->_count, $page, $this->_pagesize);
		}
		return $pages;
	}
}
?>